package org.thingsboard.tools.utils;

import com.alibaba.fastjson.JSONArray;
import io.netty.buffer.Unpooled;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.util.concurrent.Future;
import org.thingsboard.mqtt.MqttClient;
import org.thingsboard.mqtt.MqttClientConfig;
import org.thingsboard.mqtt.MqttConnectResult;
import org.thingsboard.tools.model.entity.TelemetryDo;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @title: Test
 * @Author JiangWang
 * @Date: 2022/1/7 9:43
 * @Version 1.0
 */
public class Test {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        MqttClient provision = initClient("uaoYcNfYKO1ZtJitiCwA");
        for (int i=0;i<10000;i++){
            TelemetryDo telemetryDo = new TelemetryDo();
            String devicesName = "DDW00000000";
            telemetryDo.setSn(devicesName);
            telemetryDo.setTs(System.currentTimeMillis()/1000);
            telemetryDo.setMo(1);
            telemetryDo.setRs(150);
            telemetryDo.setSi(100);
            telemetryDo.setTe(35);
            Object o = JSONArray.toJSON(telemetryDo);
            if (provision != null){
                scheduler.submit(()->{
                    provision.publish("v1/devices/me/telemetry", Unpooled.wrappedBuffer(o.toString().getBytes(StandardCharsets.UTF_8)),MqttQoS.AT_MOST_ONCE)
                        .addListener(future -> {
                            if (future.isSuccess()) {
                                System.out.println("热身遥测数据发送成功 device: "+devicesName);
                            } else {
                                System.out.println("热身遥测数据发送失败 device: "+devicesName+",错误信息:"+future.cause());
                            }
                        });
                });

            }
        }
    }
    protected static MqttClient initClient(String token){
        MqttClientConfig config = new MqttClientConfig();
        config.setUsername(token);
        MqttClient client = MqttClient.create(config, null);
        client.setEventLoop(new NioEventLoopGroup());
        Future<MqttConnectResult> connectFuture = client.connect("111.229.241.169", 1883);
        MqttConnectResult result;
        try {
            result = connectFuture.get(5, TimeUnit.SECONDS);
        } catch (Exception ex) {
            connectFuture.cancel(true);
            client.disconnect();
            throw new RuntimeException("Failed to connect to MQTT broker");
        }
        if (!result.isSuccess()) {
            connectFuture.cancel(true);
            client.disconnect();
        }
        return client;
    }
}
